package com.jutixueyuan.service.impl;

import com.jutixueyuan.pojo.Item;
import com.jutixueyuan.pojo.LivegoodsResult;
import com.jutixueyuan.service.HotProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class HotProductServiceImpl implements HotProductService {


    @Autowired
    private MongoTemplate mongoTemplate;


    @Value("${livegoods.fastdfs.nginx}")
    private String livegoodsFastDfsNginx;

    @Override
    public LivegoodsResult selectHotProduct(String city) {

        try {
            //创建条件限制对象
            Criteria criteria = Criteria.where("city").is(city);

            //条件查询对象Query
            Query query = new Query(criteria);

            //排序 以商品销售数量降序排序
            query.with(Sort.by(Sort.Order.desc("sales")));

            //分页:取前面4个商品
            query.with(PageRequest.of(0,4));


            //执行查询
            List<Item> items = mongoTemplate.find(query, Item.class);

            for (Item item : items) {
                item.setImg(this.livegoodsFastDfsNginx+item.getImg());
            }

            //组装LivegoodsResult对象
            LivegoodsResult ok = LivegoodsResult.ok(items);


            return ok;
        }catch (Exception e){
            return  LivegoodsResult.error("请求失败");
        }

    }
}
